<template>
  <div id="quota-container-uniq-002" ref="quotaContainerRef" class="quota-container">
    <router-view v-if="route.matched.length === 2" @updated="handleUpdated" />
    <a-spin v-else :spinning="!quoteApply.loaded || backgroundLoading">
      <a-space direction="vertical" :size="24">
        <e-container>
          <div style="display: flex; justify-content: space-between; align-items: center">
            <e-title :title="'Subject ' + quoteApply.raw.value.theme" />
            <div class="buttons">
              <a-space>
                <a-button v-if="isEditing || isModifing" type="primary" ghost @click="handleClickEdit">
                  <a-space><e-icon type="edit" />Edit</a-space>
                </a-button>
                <a-button v-if="isEditing || isModifing" type="primary" @click="handleClickSubmit">
                  <a-space><e-icon type="submit" />Submit</a-space>
                </a-button>
                <a-button v-if="isEditing" danger @click="handleDeleteApply">
                  <a-space><e-icon type="delete" />Delete</a-space>
                </a-button>
                <a-button v-if="isViewing && isOwner" class="secondary" @click="handleApplyModify">
                  <a-space><e-icon type="edit" />Request To Modify</a-space>
                </a-button>
                <a-button v-if="isViewing && isOwner" type="primary" @click="handleConfirmPrice">
                  <a-space><e-icon type="correct" />Client Approved</a-space>
                </a-button>
                <a-button v-if="isWaitForPricing" class="secondary" @click="handleRevokePrice">
                  <a-space><e-icon type="repeal" />Revoke</a-space>
                </a-button>
                <a-button v-if="isOwner" @click="handleGetOperationLog">
                  <a-space><e-icon type="records" />View Operation Logs</a-space>
                </a-button>
                <a-button
                  v-if="isPricing && quoteApply.raw.value.clientQuoteApplyServicePrice"
                  type="primary"
                  :loading="completeButtonLoading"
                  @click="handleCompleteApply"
                >
                  <a-space>
                    <e-icon type="correct" />
                    Complete
                  </a-space>
                </a-button>
                <!-- 未开始报价可以退回 -->
                <a-button
                  v-if="isPricing && !quotaHasBegun"
                  class="secondary"
                  :loading="returnLoading"
                  @click="returnTheApply"
                >
                  <a-space>
                    <e-icon type="repeal" />
                    Return
                  </a-space>
                </a-button>
                <a-button v-if="isReviewing" type="primary" @click="handlePassApply">
                  <a-space>
                    <e-icon type="correct" />
                    Approve
                  </a-space>
                </a-button>
              </a-space>
            </div>
          </div>
        </e-container>
        <a-tabs v-model:activeKey="activeKey" type="card">
          <a-tab-pane :key="0" tab="Client Info">
            <e-container with-tab>
              <quota-detail :apply="quoteApply" :background-info="clientBackgroundInfo" :readonly="isCompleted" />
            </e-container>
          </a-tab-pane>
          <a-tab-pane v-if="isPricing || isReviewing || isViewing" :key="1" tab="Service Price">
            <e-container with-tab>
              <price-view
                ref="priceViewRef"
                :apply="quoteApply"
                :available-language-pairs="availableLanguagePairs"
                :reviewing="isReviewing"
                :readonly="!isPricing"
                @load-price="reload"
              />
            </e-container>
          </a-tab-pane>
        </a-tabs>
        <a-modal
          v-model:visible="showOperationLogModal"
          width="888px"
          title="Operation Logs"
          wrap-class-name="primary-modal"
          :footer="null"
          @cancel="showOperationLogModal = false"
        >
          <a-list bordered :data-source="operationLogs" class="operation-logs">
            <template #renderItem="{ item }">
              <a-list-item>{{ item }}</a-list-item>
            </template>
          </a-list>
        </a-modal>
        <a-modal
          v-model:visible="showPriceManagerModal"
          width="888px"
          title="Choose Price Manager"
          wrap-class-name="primary-modal"
          ok-text="Complete"
          @cancel="showConfigurationItemsModal = false"
          @ok="handleSendToPriceManager"
        >
          <a-form layout="vertical">
            <a-form-item label="Price Manager" name="priceManager">
              <a-select v-model:value="priceManager" option-filter-prop="label" placeholder="Please Select">
                <a-select-option v-for="item in priceManagers" :key="item.empID" :label="item.empName">
                  {{ item.empName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-modal>
      </a-space>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, watch, computed, inject, provide, reactive, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import EIcon from '@/components/EIcon.vue'
import QuotaDetail from './QuotaDetail.vue'
import PriceView from './PriceView.vue'
import { useQuoteApply } from '@/pages/Client/hooks/useQuoteApply.js'
import { useClientBackgroundInfo } from '@/pages/Client/hooks/useClientBackgroundInfo.js'
import ServicePrice from '@/api/client/servicePrice.js'
import Client from '@/api/client/index.js'
import {
  APPLY_DELETED,
  APPLY_PASSED,
  COMPLETE_PRICE,
  SURE_TO_DELETE_APPLY,
  SURE_TO_CONFIRM_APPLY,
  SURE_TO_PASS_APPLY,
  APPLY_SUBMITTED,
  SURE_CONFIRM_COMPLETE,
  APPLY_EDIT_FIRST,
  QUOTATION_NOT_COMPLETED,
  EVALUATION_NOT_COMPLETED,
  SURE_CONFIRM_MODIFY,
  SURE_CONFIRM_PRICE,
  SURE_CONFIRM_RETURN,
  SURE_REVOKE_PRICE,
  APPLY_RETURNED
} from '@/constants/message.js'
import { useScrollEvent } from '@/hooks/useScrollEvent.js'
const { Modal, message } = inject('Feedback')
const route = useRoute()
const router = useRouter()
const store = useStore()
const applyId = route.params.id
const activeKey = ref(0)
const availableLanguagePairs = ref([])
const priceManagers = ref([])
const { quoteApply, reload } = useQuoteApply(applyId, () => {})
const isOwner = computed(() => quoteApply.raw.value.createBy === store.state.user.userInfo.userID)
const isBum = computed(() => quoteApply.raw.value.bumid === store.state.user.userInfo.userID)
const isPriceManager = computed(() => quoteApply.raw.value.apid === store.state.user.userInfo.userID)
// 销售编辑首次需求状态
const isEditing = computed(() => isOwner.value && quoteApply.raw.value.status === 10)
// 销售请求修改状态
const isModifing = computed(() => isOwner.value && quoteApply.raw.value.status === 15)
// 销售和BUM查看状态
const isViewing = computed(() => (isOwner.value || isBum.value) && quoteApply.raw.value.status === 30)
// 申请人等待报价状态
const isWaitForPricing = computed(() => isOwner.value && quoteApply.raw.value.status === 20)
// BUM报价状态
const isPricing = computed(() => isBum.value && quoteApply.raw.value.status === 20)
// 已经开始报价
const quotaHasBegun = computed(
  () =>
    Array.isArray(quoteApply.raw.value.clientQuoteApplyServicePrice) &&
    quoteApply.raw.value.clientQuoteApplyServicePrice.length > 0
)
// 价格管理员审核状态
const isReviewing = computed(() => isPriceManager.value && quoteApply.raw.value.status === 25)
// 完结状态
const isFinish = computed(() => isOwner.value && quoteApply.raw.value.status === 40)
provide('permissions', {
  isOwner,
  isBum,
  isPriceManager,
  isEditing,
  isViewing,
  isPricing,
  isReviewing
})
const clientBackgroundInfo = reactive({
  raw: {
    cbgDemandType: [],
    cbg: {},
    cbgValue: {}
  },
  transformed: {
    cbgDemandType: [],
    cbg: {}
  },
  loaded: false
})
const backgroundLoading = ref(true)
const isCompleted = computed(() => quoteApply.raw.value.status === 30)
watch(
  () => quoteApply.loaded.value,
  loaded => {
    if (loaded) {
      backgroundLoading.value = true
      new Promise(resolve => {
        useClientBackgroundInfo(quoteApply.raw.value.clientInfo.id, resolve, true)
      })
        .then(({ raw, transformed }) => {
          clientBackgroundInfo.raw = raw.value
          clientBackgroundInfo.transformed = transformed.value
        })
        .finally(() => {
          backgroundLoading.value = false
        })
      // 获取可用的语言对
      ServicePrice.getLanguagePair(quoteApply.raw.value.clientInfo.id, quoteApply.raw.value.clientInfo.fromGrade).then(
        ({ data }) => {
          availableLanguagePairs.value = data
        }
      )
      // 获取价格管理员
      ServicePrice.getPriceManagers(quoteApply.raw.value.clientInfo.id).then(({ data }) => {
        priceManagers.value = data
      })
    }
  }
)
const showPriceManagerModal = ref(false)
const priceManager = ref(null)
const priceViewRef = ref(null)
const completeButtonLoading = ref(false)
const returnLoading = ref(false)
// 完成报价
const handleCompleteApply = () => {
  completeButtonLoading.value = true
  ServicePrice.getQuoteApply(quoteApply.raw.value.id).then(({ data }) => {
    if (data.clientQuoteApplyServicePrice === null) {
      completeButtonLoading.value = false
      message.error(QUOTATION_NOT_COMPLETED)
    } else {
      Client.getBackgroundInfo(quoteApply.raw.value.client).then(({ data }) => {
        if (data.cbgValue === null) {
          completeButtonLoading.value = false
          message.error(EVALUATION_NOT_COMPLETED)
        } else {
          activeKey.value = 1
          nextTick(() => {
            priceViewRef.value.handleSaveServicePrice(true).then(() => {
              completeButtonLoading.value = false
              Modal.confirm({
                content: SURE_CONFIRM_COMPLETE,
                okText: 'Confirm',
                onOk: () => {
                  ServicePrice.completeApply(quoteApply.raw.value.id).then(({ data }) => {
                    // 表示需要价格管理员介入
                    if (data === -2) {
                      showPriceManagerModal.value = true
                    } else {
                      message.success(COMPLETE_PRICE)
                      reload()
                    }
                  })
                }
              })
            })
          })
        }
      })
    }
  })
}
// 退回给发起人
const returnTheApply = () => {
  Modal.confirm({
    content: SURE_CONFIRM_RETURN,
    okText: 'Confirm',
    onOk: () => {
      returnLoading.value = true
      ServicePrice.returnApply(quoteApply.raw.value.id)
        .then(() => {
          message.success(APPLY_RETURNED)
          reload()
        })
        .finally(() => {
          returnLoading.value = false
        })
    }
  })
}
const handleSendToPriceManager = async () => {
  if (!priceManager.value) {
    message.warning('Please select a price manager')
  } else {
    try {
      await ServicePrice.savePriceManager(quoteApply.raw.value.id, priceManager.value)
      await ServicePrice.sendToPriceManager(quoteApply.raw.value.id)
      showPriceManagerModal.value = false
      message.success(COMPLETE_PRICE)
      reload()
    } catch (e) {
      message.error(e)
    }
  }
}
const quotaContainerRef = ref(null)
const handleUpdated = () => {
  reload()
  setTimeout(() => {
    quotaContainerRef.value.scrollTop = 0
  }, 0)
}
// 监听滚动
onMounted(() => {
  quotaContainerRef.value.addEventListener('scroll', useScrollEvent)
})
const handleClickEdit = () => {
  router.push({ name: 'Edit Price Application', params: { id: quoteApply.raw.value.id } })
}
const handleClickSubmit = () => {
  Client.getBackgroundInfo(quoteApply.raw.value.client).then(({ data }) => {
    if (data.cbgDemandType.length === 0) {
      message.error(APPLY_EDIT_FIRST)
    } else {
      Modal.confirm({
        content: SURE_TO_CONFIRM_APPLY,
        okText: 'Confirm',
        onOk: () => {
          ServicePrice.submitQuoteApply(quoteApply.raw.value.id).then(() => {
            message.success(APPLY_SUBMITTED)
            reload()
            window.opener.location.reload()
          })
        }
      })
    }
  })
}
const handleDeleteApply = () => {
  Modal.confirm({
    content: SURE_TO_DELETE_APPLY,
    okText: 'Delete',
    onOk: () => {
      ServicePrice.deleteQuoteApply(quoteApply.raw.value.id).then(() => {
        message.success(APPLY_DELETED)
        setTimeout(() => {
          window.close()
          window.opener.location.reload()
        }, 1000)
      })
    }
  })
}
const handlePassApply = () => {
  Modal.confirm({
    content: SURE_TO_PASS_APPLY,
    okText: 'Approve',
    onOk: () => {
      ServicePrice.passQuoteApply(quoteApply.raw.value.id).then(() => {
        reload()
        message.success(APPLY_PASSED)
      })
    }
  })
}
const showOperationLogModal = ref(false)
const operationLogs = ref([])
const handleGetOperationLog = () => {
  ServicePrice.getOperationLog(quoteApply.raw.value.id).then(({ data }) => {
    showOperationLogModal.value = true
    operationLogs.value = data
  })
}
const handleApplyModify = () => {
  Modal.confirm({
    content: SURE_CONFIRM_MODIFY,
    onOk: () => {
      ServicePrice.applyModify(quoteApply.raw.value.id).then(() => {
        reload()
        window.opener.location.reload()
      })
    }
  })
}
const handleConfirmPrice = () => {
  Modal.confirm({
    content: SURE_CONFIRM_PRICE,
    onOk: () => {
      ServicePrice.confirmPrice(quoteApply.raw.value.id).then(() => {
        reload()
        window.opener.location.reload()
        window.close()
      })
    }
  })
}
// 申请人撤回
const handleRevokePrice = () => {
  Modal.confirm({
    content: SURE_REVOKE_PRICE,
    onOk: () => {
      ServicePrice.revokeQuoteApply(quoteApply.raw.value.id).then(() => {
        reload()
        window.opener.location.reload()
      })
    }
  })
}
</script>

<style lang="less" scoped>
@import '@/assets/style/reset_tabs';
.quota-container {
  width: 100%;
  min-width: 1200px;
  height: 100%;
  padding: 24px;
  overflow: auto;
}
@shadow-color: rgba(182, 188, 224, 0.45);
.ant-space {
  width: 100%;
}
.operation-logs {
  :deep(.ant-list-header) {
    background-color: @milk;
    color: @text-gray;
    font-weight: bold;
  }
}
</style>
